﻿using PermissionDesign.Model;
using PermissionDesign.Model.Entity;
using PermissionDesign.Model.Permission;
using PermissionDesign.Model.Request;
using PermissionDesign.Model.Response;
using PermissionDesign.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace PermissionDesign.Service
{
    /// <summary>
    /// 角色服务
    /// </summary>
    public class RoleService : BaseService
    {
        private ActionInfoList _actionInfoList;

        //继承父类中有参构造函数
        public RoleService(DataContext dbContext, ActionInfoList actionInfoList) : base(dbContext)
        {
            _dbContext = dbContext;
            _actionInfoList = actionInfoList;
        }

        #region 查询所有角色
        /// <summary>
        /// 查询所有角色
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public ResponseModel GetRoles(Expression<Func<Role, bool>> where)
        {
            var roles = _dbContext.Role.Where(where).ToList();
            var response = new ResponseModel();
            response.code = 200;
            response.data = new List<Response_Role>();
            foreach (var role in roles)
            {
                response.data.Add(new Response_Role
                {
                    Id = role.Id,
                    RoleEncoding = role.RoleEncoding,
                    RoleName = role.RoleName,
                    RoleDesc = role.RoleDesc,
                    AddDate = role.AddDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Remark = role.Remark
                });
            }
            return response;
        }
        #endregion

        #region 分页查询系统角色
        /// <summary>
        /// 分页查询系统角色
        /// </summary>
        /// <param name="where"></param>
        /// <param name="total"></param>
        /// <param name="pageIndex"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public ResponseModel RolePageQuery(List<Expression<Func<Role, bool>>> where, out int total, int pageIndex = 1, int pageSize = 10)
        {
            //查询出除超级管理员外的角色信息
            var list = _dbContext.Role.Where(c => c.RoleEncoding != EnumHelper.SingleTon().GetEnumDescription(EnumConfig.SuperAdminEncoding));
            foreach (var item in where)
            {
                list = list.Where(item);
            }
            total = list.Count();
            var pageData = list.OrderByDescending(c => c.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var response = new ResponseModel();
            response.code = 200;
            response.data = new List<Response_Role>();
            foreach (var role in pageData)
            {
                response.data.Add(new Response_Role
                {
                    Id = role.Id,
                    RoleEncoding = role.RoleEncoding,
                    RoleName = role.RoleName,
                    RoleDesc = role.RoleDesc.Length > 50 ? role.RoleDesc.Substring(0, 50) + "..." : role.RoleDesc,
                    AddDate = role.AddDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    Remark = role.Remark
                });
            }
            return response;
        }
        #endregion

        #region 查询角色是否存在
        /// <summary>
        /// 查询角色是否存在
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public bool IsRoleExist(Expression<Func<Role, bool>> where)
        {
            return _dbContext.Role.FirstOrDefault(where) != null;
        }
        #endregion

        #region 添加角色
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResponseModel AddRole(Request_AddRole model)
        {
            var role = new Role
            {
                RoleEncoding = model.RoleEncoding,
                RoleName = model.RoleName,
                RoleDesc = model.RoleDesc,
                AddDate = DateTime.Now,
                Remark = model.Remark
            };

            _dbContext.Role.Add(role);
            int i = _dbContext.SaveChanges();
            if (i > 0)
            {
                return new ResponseModel { code = 200, result = "添加角色成功" };
            }
            else
            {
                return new ResponseModel { code = 0, result = "添加角色失败" };
            }
        }
        #endregion

        #region 编辑角色
        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="editRole"></param>
        /// <returns></returns>
        public ResponseModel EditRole(Request_EditRole editRole)
        {
            if (!this.IsRoleExist(c => c.Id == editRole.editId))
            {
                //角色不存在
                return new ResponseModel { code = 0, result = "角色不存在" };
            }

            var role = _dbContext.Role.Find(editRole.editId);
            role.RoleName = editRole.editRoleName;
            role.RoleDesc = editRole.editRoleDesc;
            role.Remark = editRole.editRemark;
            _dbContext.Role.Update(role);
            int i = _dbContext.SaveChanges();
            if (i > 0)
            {
                return new ResponseModel { code = 200, result = "更新角色成功" };
            }
            else
            {
                return new ResponseModel { code = 0, result = "更新角色失败" };
            }
        }
        #endregion

        #region 查询一个角色信息
        /// <summary>
        /// 查询一个角色信息
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public ResponseModel GetOneRole(Expression<Func<Role, bool>> where)
        {
            if (!this.IsRoleExist(where))
            {
                return new ResponseModel { code = 0, result = "角色不存在" };
            }

            var role = _dbContext.Role.First(where);
            var response = new ResponseModel();
            response.code = 200;
            response.data = new Response_Role
            {
                Id = role.Id,
                RoleEncoding = role.RoleEncoding,
                RoleName = role.RoleName,
                RoleDesc = role.RoleDesc,
                AddDate = role.AddDate.ToString("yyyy-MM-dd HH:mm:ss"),
                Remark = role.Remark
            };
            return response;
        }
        #endregion

        #region 根据角色编号获取角色功能集合
        /// <summary>
        /// 根据角色编号获取角色功能集合
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        public string GetActionByRoleId(int roleId)
        {
            //角色不存在
            if (!this.IsRoleExist(c => c.Id == roleId))
            {
                return "";
            }

            var res_role = this.GetOneRole(c => c.Id == roleId);
            if (res_role.code == 200)
            {
                var role = res_role.data as Response_Role;
                //超级管理员拥有所有功能权限
                if (role.RoleEncoding == EnumHelper.SingleTon().GetEnumDescription(EnumConfig.SuperAdminEncoding))
                {
                    var arr = _actionInfoList.actionInfoList.Select(c => c.ActionEncoding).ToArray();
                    return string.Join(",", arr);//用逗号将功能编码连接
                }

                //当前角色没有对应的功能权限
                if (_dbContext.RoleAction.FirstOrDefault(c => c.RoleId == roleId) == null)
                {
                    return "";
                }
                else
                {
                    return _dbContext.RoleAction.FirstOrDefault(c => c.RoleId == roleId).ActionEncodings;
                }
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 为角色授予功能权限
        /// <summary>
        /// 为角色授予功能权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="actionEncodings">功能编码</param>
        /// <returns></returns>
        public ResponseModel Authorize(int roleId, string actionEncodings)
        {
            var roleAction = _dbContext.RoleAction.FirstOrDefault(c => c.RoleId == roleId);
            //RoleAction表中没有当前角色的信息
            if (roleAction == null)
            {
                _dbContext.RoleAction.Add(
                    new RoleAction
                    {
                        RoleId = roleId,
                        ActionEncodings = actionEncodings,
                        Remark = DateTime.Now + "为角色授予功能权限"
                    });
            }
            else
            {
                //修改RoleAction表当前角色的功能权限信息
                roleAction.ActionEncodings = actionEncodings;
                _dbContext.RoleAction.Update(roleAction);
            }

            var i = _dbContext.SaveChanges();
            if (i > 0)
            {
                return new ResponseModel { code = 200, result = "角色授权成功" };
            }
            else
            {
                return new ResponseModel { code = 0, result = "角色授权失败" };
            }
        }
        #endregion

    }
}
